/**
 * Copyright (c) 2017 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
 */

package com.hyyt.shopjsp.wxmg.basicInfo.controller;

import com.hyyt.shopjsp.common.controller.BaseController;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.StringStaticKey;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.json.FastJsonUtils;
import com.hyyt.shopjsp.util.redis.util.RedisDataReadUtil;
import com.hyyt.shopjsp.wxmg.basicInfo.pojo.WxMenuInfo;
import com.hyyt.shopjsp.wxmg.basicInfo.service.IWxMenuInfoService;
import com.hyyt.shopjsp.wxmg.util.WxBasicUtil;
import com.hyyt.shopjsp.wxmg.util.WxMenuUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Liu Ling on 2017/11/10 0010.
 *
 * WX_微信菜单信息
 */
@Controller
@RequestMapping("/back/wx/menuInfo")
public class WxMenuInfoController extends BaseController {

    private Logger logger = Logger.getLogger(WxMenuInfoController.class);
    private String basePath = "/back/wxmg/menu/";

    @Resource
    private IWxMenuInfoService wxMenuInfoService;

    /**
     *进入微信菜单信息页面
     *
     * @return 返回到指定页面
     */
    @RequestMapping("gotoMenuInfoPage")
    public String gotoMenuInfoPage (Map<String, Object> param){
        // 获取微信凭证 ticket
        String ticket = RedisDataReadUtil.getRedisValue(StringStaticKey.WX_TICKET);
        // 获取微信公众号二维码图片地址
        String qrCodeURL = WxBasicUtil.getQRCodeImageUrl(ticket);
        param.put("qrCodeURL", qrCodeURL);
        return basePath + "menuList";
    }

    /**
     *查询微信菜单列表
     *
     * @param response 返回结果集
     */
    @RequestMapping(value = "listMenuInfo",method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg listMenuInfo(HttpServletResponse response){
        List <WxMenuInfo> firstWxMenuInfoList=wxMenuInfoService.queryAllWxMenuInfo();
        return ResultMsg.create(true,null,FastJsonUtils.toJSONString(firstWxMenuInfoList));
    }

    /**
     *查询一级微信菜单数量
     *
     */
    @RequestMapping(value = "queryFirstMenuNo",method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg queryFirstMenuNo(){
        Map<String,Object> param = new HashMap<>();
        int count=wxMenuInfoService.countWxMenuInfo(param);
        param.put("count",count);
        return  ResultMsg.create(true,null,FastJsonUtils.toJSONString(param));
    }

    /**
     *查询二级微信菜单数量
     *
     * @param parentId 父id
     * @param wxmiId 微信菜单id
     */
    @RequestMapping(value = "querySecondMenuNo",method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg querySecondMenuNo(Integer parentId,Integer wxmiId){
        if (Utils.objectIsNotEmpty(parentId)){
            Map<String,Object> param = new HashMap<>();
            param.put("parentId",parentId);
            int count=wxMenuInfoService.countWxSecondMenuInfo(param);
            param.clear();
            param.put("wxmiId",wxmiId);
            List<WxMenuInfo> list=wxMenuInfoService.queryWxMenuInfo(param);
            param.clear();
            param.put("list",list);
            param.put("count",count);
            return  ResultMsg.create(true,null,FastJsonUtils.toJSONString(param));
        }else {
            return ResultMsg.create(false);
        }
    }

    /**
     * 根据id获得微信菜单对象
     *
     * @param wxmiId 微信菜单信息ID
     * @return
     */
    @RequestMapping(value = "getMenuInfoObject",method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg getMenuInfoObject(Integer wxmiId){
        if (Utils.objectIsNotEmpty(wxmiId)){
            WxMenuInfo wxMenuInfo = wxMenuInfoService.loadWxMenuInfo(wxmiId);
            return ResultMsg.create(true,null, FastJsonUtils.toJSONString(wxMenuInfo));
        }else{
            return ResultMsg.create(false);
        }
    }

    /**
     * 保存或者修改微信菜单信息
     *
     * @param wxMenuInfo 微信菜单信息对象
     * @return 返回布尔值
     */
    @RequestMapping(value = "saveOrUpdateMenuInfo",method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg saveOrUpdateMenuInfo(WxMenuInfo wxMenuInfo){
        if (Utils.objectIsNotEmpty(wxMenuInfo)){
            if (Utils.objectIsEmpty(wxMenuInfo.getWxmiId())){
                wxMenuInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
                wxMenuInfo.setLastUpdateDate(new Timestamp(System.currentTimeMillis()));
                wxMenuInfoService.saveWxMenuInfo(wxMenuInfo);
            }else{
                wxMenuInfo.setLastUpdateDate(new Timestamp(System.currentTimeMillis()));
                wxMenuInfoService.updateWxMenuInfo(wxMenuInfo);
            }
            return ResultMsg.create(true);
        }else {
            return ResultMsg.create(false);
        }
    }

    /**
     * 根据id删除微信菜单信息
     *
     * @param wxmiId 微信菜单信息id
     * @return 返回布尔值
     */
    @RequestMapping(value = "deleteMenuInfo",method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg deleteMenuInfo(Integer wxmiId){
        if (Utils.objectIsNotEmpty(wxmiId)){
            wxMenuInfoService.deleteWxMenuInfo(wxmiId);
            return ResultMsg.create(true);
        }else{
            return ResultMsg.create(false);
        }
    }

    /**
     * 生成微信菜单预览
     *
     * @return 对象集合
     */
    @RequestMapping(value = "previewMenuInfo",method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg previewMenuInfo(){
        return ResultMsg.create(true,"生成微信菜单预览",wxMenuInfoService.getMenuJsonString(wxMenuInfoService.queryAllWxMenuList()));
    }

    /**
     * 生成微信服务器上的菜单
     *
     * @return 对象集合
     */
    @RequestMapping(value = "createWxMenu",method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg createWxMenu(){
        String access_token = RedisDataReadUtil.getRedisValue(StringStaticKey.WX_ACCESS_TOKENS);
        //创建微信菜单,返回微信响应的信息
        String stringJson = WxMenuUtil.createWxMenu(access_token,wxMenuInfoService.getMenuJsonString(wxMenuInfoService.queryAllWxMenuList()));
        String message = "创建菜单失败！";
        if(Utils.objectIsNotEmpty(stringJson)){
            //{"errcode":0,"errmsg":"ok"}
            Map map = FastJsonUtils.stringToCollect(stringJson);
            if("0".equals(String.valueOf(map.get("errcode"))) && "ok".equals(map.get("errmsg"))){
                message = "创建成功!";
            } else{
                //注意这里后期做一个全局返回码表的对照，同时显示对应的错误信息,默认全局返回码表加载在上下文中。
                message = "创建菜单失败：" + stringJson;
            }
        }
        return ResultMsg.create(true,"生成微信服务器上的菜单", message);
    }

    /**
     * 获取微信服务器菜单信息
     *
     * @return 对象集合
     */
    @RequestMapping(value = "getWxMenu",method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg getWxMenu(){
        String access_token = RedisDataReadUtil.getRedisValue(StringStaticKey.WX_ACCESS_TOKENS);
        //创建微信菜单,返回微信响应的信息
        String menuJsonString = WxMenuUtil.getMenu(access_token);
        return ResultMsg.create(true,"获取微信服务器菜单信息", menuJsonString);
    }

    /**
     * 删除微信服务器菜单信息
     *
     * @return 对象集合
     */
    @RequestMapping(value = "deleteWxMenu",method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg deleteWxMenu(){
        String access_token = RedisDataReadUtil.getRedisValue(StringStaticKey.WX_ACCESS_TOKENS);
        //创建微信菜单,返回微信响应的信息
        Map<String, String> messageMap = WxMenuUtil.deleteMenu(access_token);
        String message = "菜单删除失败！";
        if(Utils.objectIsNotEmpty(messageMap)){
            if("0".equals(String.valueOf(messageMap.get("errcode"))) && "ok".equals(messageMap.get("errmsg"))){
                message = "菜单删除成功!";
            } else{
                //注意这里后期做一个全局返回码表的对照，同时显示对应的错误信息,默认全局返回码表加载在上下文中。
                message = "菜单删除失败：" + FastJsonUtils.toJSONString(messageMap);
            }
        }
        return ResultMsg.create(true,"删除微信服务器菜单信息", message);
    }

}
